/*	
 * Authors: Ken YANG <spng.yang@gmail.com>
 * 	
 * Mammoth client main program
 *
 * Copyright (C) 2007-2008 Ken YANG
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, version 2. 
 * THIS SOFTWARE COMES "AS IS" WITHOUT ANY WARRANTIES.
 */

#include "error.h"

int daemon_p=0;	/* if daemon */
static void err_core(int errnoflag, int level, const char *fmt,
		va_list vp);


/* "Real" error handle, has errno */

/* Fatal error, print msg and terminate */
void err_sys(const char *fmt, ...)
{
	va_list vp;
	va_start(vp, fmt);
	err_core(1, LOG_ERR, fmt, vp);
	va_end(vp);
	exit(1);
}

/* Nonfatal error, print msg and return */
int err_ret(const char *fmt, ...)
{
	va_list vp;
	va_start(vp,fmt);
	err_core(1, LOG_INFO, fmt, vp);
	va_end(vp);
	return 1;
}

/* Fatal error, print msg, dump and terminate */
void err_dump(const char *fmt, ...)
{
	va_list vp;
	va_start(vp, fmt);
	err_core(1, LOG_ERR, fmt, vp);
	va_end(vp);
	abort();
}

/* End - Real */

/* "Pesudo" error handle, no errno */
void err_quit(const char *fmt, ...)
{
	va_list vp;
	va_start(vp, fmt);
	err_core(0, LOG_ERR, fmt, vp);
	va_end(vp);
	exit(1);
}

int err_msg(const char *fmt, ...)
{
	va_list vp;
	va_start(vp,fmt);
	err_core(0, LOG_INFO, fmt, vp);
	va_end(vp);
	return 1;
}

/* Core error handle */
static void err_core(int errnoflag, int level, const 
		char *fmt, va_list vp)
{
	int errno_bk, len;
	char buff[MAXLINE];

	errno_bk = errno;	/* backup errno */

	vsnprintf(buff, MAXLINE-1, fmt, vp);

	len=strlen(buff);

	if(errnoflag){
		snprintf(buff+len, MAXLINE-len, ":%s", strerror(errno_bk));
	}

	strcat(buff, "\n");

	if(daemon_p){
		syslog(level,buff);
	}else {
		fflush(stderr);
		fputs(buff, stderr);
		fflush(stderr);
	}

}



